package org.example.springmvc_demo7.controller;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.springmvc_demo7.model.BookInfo;
import org.example.springmvc_demo7.model.PageRequest;
import org.example.springmvc_demo7.model.PageResult;
import org.example.springmvc_demo7.model.Result;
import org.example.springmvc_demo7.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RequestMapping("book")
@RestController
public class BookController {
    @Autowired
    private BookService bookService;

    @RequestMapping("/addBook")
    public String addBook(BookInfo bookInfo){
        //校验参数
        log.info("添加图书, 接收到参数bookInfo: {}", bookInfo);

        if (!StringUtils.hasLength(bookInfo.getBookName())
                || !StringUtils.hasLength(bookInfo.getAuthor())
                || bookInfo.getCount()==null
                || bookInfo.getPrice()==null
                || !StringUtils.hasLength(bookInfo.getPublish())
                || bookInfo.getStatus()==null){
            return "输入参数不合法";
        }
        try{
            Integer result = bookService.insertBook(bookInfo);
            if (result >0){
                return "";
            }
        }catch (Exception e){
            log.error("添加图书异常, e: ", e);
        }

        return "添加失败";
    }

    @RequestMapping("/getBookListByPage")
    public Result<PageResult<BookInfo>> getBookListByPage(PageRequest pageRequest, HttpSession session){
        log.info("查询图书列表:请求参数pageRequest: {}", pageRequest);

        PageResult<BookInfo> bookList = bookService.getBookListByPage(pageRequest);
        return Result.success(bookList);

    }

    @RequestMapping("/updateBook")
    public String updateBook(BookInfo bookInfo){
        log.info("更新图书,bookInfo:{}",bookInfo);
        try{
            Integer result = bookService.updateBookById(bookInfo);
            if (result>0){
                return "";
            }
            return "内部错误, 请联系管理员";

        } catch (Exception e){
            log.error("图书更新失败:e",e);
            return "内部错误,请联系管理员";
        }
    }

    @RequestMapping("/deleteBook")
    public Boolean deleteBook(Integer bookId){
        log.info("删除图书, bookId: {}", bookId);
        Integer result = bookService.deleteBook(bookId);
        if (result>0){
            return true;
        }
        return false;

    }

    public String BatchDelete(@RequestParam List<Integer> ids){
        log.info("批量删除图书, ids: {}", ids);
        Integer result = bookService.batchDeleteBookByIds(ids);
        if (result >0){
            return "";
        }
        return "删除失败, 请联系管理员";
    }
}
